﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PhoneBilling.Models;
using PhoneBilling.Report;
using System.IO;

namespace PhoneBilling.Controllers
{
    public class BillingController : Controller
    {
        //
        // GET: /Billing/

        public ActionResult Index()
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            MenuModel model = (MenuModel)Session["Menu"];
            model.SetMenu("Billing");
            return View();
        }

        public ActionResult Account()
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            SanDiDbsEntities entities = new SanDiDbsEntities();

            Guid userID = (Guid)Session["UserID"];
            var authroity = (from a in entities.UserAuthority
                             where a.Item == "结账" &&
                                   a.UserID == userID
                             select a).SingleOrDefault();
            if (authroity == null || !authroity.Allow)
            {
                TempData["Error"] = "你没有权限使用这个功能";
                return RedirectToAction("Error", "Shared");
            }

            MenuModel model1 = (MenuModel)Session["Menu"];
            model1.SetMenu("Billing", "Billing/Account");

            AccountModel model = new AccountModel();
            model.年 = DateTime.Now.Year;
            model.月 = DateTime.Now.Month;
            model.年List = new List<int>();
            model.年List.Add(model.年 - 2);
            model.年List.Add(model.年 - 1);
            model.年List.Add(model.年);
            model.年List.Add(model.年 + 1);

            model.月List = new List<int>();
            model.月List.Add(1);
            model.月List.Add(2);
            model.月List.Add(3);
            model.月List.Add(4);
            model.月List.Add(5);
            model.月List.Add(6);
            model.月List.Add(7);
            model.月List.Add(8);
            model.月List.Add(9);
            model.月List.Add(10);
            model.月List.Add(11);
            model.月List.Add(12);

            return View(model);
        }

        [HttpPost]
        public ActionResult Account(AccountModel model)
        {
            if (ModelState.IsValid)
            {
                return RedirectToAction("AccountResult", "Billing", new { myear = model.年, mmonth = model.月 });
            }

            model.年List = new List<int>();
            model.年List.Add(model.年 - 2);
            model.年List.Add(model.年 - 1);
            model.年List.Add(model.年);
            model.年List.Add(model.年 + 1);

            model.月List = new List<int>();
            model.月List.Add(1);
            model.月List.Add(2);
            model.月List.Add(3);
            model.月List.Add(4);
            model.月List.Add(5);
            model.月List.Add(6);
            model.月List.Add(7);
            model.月List.Add(8);
            model.月List.Add(9);
            model.月List.Add(10);
            model.月List.Add(11);
            model.月List.Add(12);
            return View(model);
        }

        public class MonthFee
        {
            public string GradeID { get; set; }
            public decimal 月租费 { get; set; }
            public decimal 功能费 { get; set; }
            public decimal 代维费 { get; set; }
            public decimal 免费额 { get; set; }
            public decimal 其他费 { get; set; }
        }

        private Dictionary<string, MonthFee> monthFeeDic;
        private void getMonthFeeList(SanDiDbsEntities entities)
        {
            var list = from g in entities.Grades
                       where g.FeeType == "R"
                       select g;
            monthFeeDic = new Dictionary<string, MonthFee>();
            foreach (var item in list)
            {
                MonthFee monthFee = new MonthFee();
                monthFee.月租费 = item.ServeRatio;
                monthFee.功能费 = item.BaseToExtra;
                monthFee.代维费 = item.BaseToServe;
                monthFee.免费额 = item.ExtraToServe;
                monthFee.其他费 = item.FeeMin;

                monthFeeDic.Add(item.GradeID.Trim(), monthFee);
            }
        }


        public ActionResult AccountResult(int myear, int mmonth)
        {
            try
            {
                DateTime month = new DateTime(myear, mmonth, 1);
                DateTime startDate = month;
                DateTime endDate = month.AddMonths(1).AddMilliseconds(-5);
                DateTime day = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
                SanDiDbsEntities entities = new SanDiDbsEntities();
                var temp = (from a in entities.NAccount
                            where a.Month == month
                            select a).FirstOrDefault();
                if (temp != null)
                {
                    TempData["Error"] = "这个月已经结账";
                    return RedirectToAction("ErrorOnly", "Shared");
                }

                getMonthFeeList(entities);
                List<UIAccount> resultList = new List<UIAccount>();

                var deptList = from d in entities.NDepartment
                               orderby d.Seq
                               select d;

                foreach (var dept in deptList)
                {
                    var groupList = from g in entities.NGroup
                                    where g.ParentType.Trim() == "Department" &&
                                          g.ParentID.Trim() == dept.ID.Trim()
                                    orderby g.Seq
                                    select g;

                    foreach (var group in groupList)
                        deal(group, dept, entities, month, day, startDate, endDate, resultList);
                }

                entities.SaveChanges();

                return View(resultList);
            }
            catch (Exception e)
            {
                TempData["Error"] = e.Message;
                return RedirectToAction("ErrorOnly", "Shared");
            }
            // 如果我们进行到这一步时某个地方出错，则重新显示表单
        }

        private void deal(NGroup ngroup, NDepartment dept, SanDiDbsEntities entities, DateTime month, DateTime day, DateTime startDate, DateTime endDate, List<UIAccount> resultList)
        {
            var extensionList = (from e in entities.Extensions
                                 where e.GrpNo.Trim() == ngroup.ID.Trim()
                                 orderby e.Seq
                                 select e);

            foreach (var extension in extensionList)
            {
                NAccount account = new NAccount();
                account.ID = Guid.NewGuid();
                account.HasPay = false;
                account.ExtensionID = extension.ExtNo.Trim();
                account.GroupID = extension.GrpNo.Trim();
                account.DepartmentID = dept.ID.Trim();
                if (account.DepartmentID == null)
                    continue;
                account.Month = month;
                account.Remark = string.Empty;
                account.AccountDate = day;

                MonthFee monthFee = monthFeeDic[extension.GradeID.Trim()];
                account.Fee1 = monthFee.月租费;
                account.Fee2 = monthFee.功能费;
                account.Fee3 = monthFee.代维费;
                account.Fee4 = monthFee.其他费;
                account.FreeFee = monthFee.免费额;
                account.Fee5 = extension.MiscFee;

                var phnList = (from p in entities.PhnToday
                               where p.CallerID.Trim() == account.ExtensionID &&
                                     p.EndTime >= startDate &&
                                     p.EndTime <= endDate &&
                                     p.Slices != null && p.Price != null && p.BaseFee != null && p.ServeFee != null && p.ExtraFee != null
                               select p).ToList();

                var tempList = (from p in phnList
                                where p.AreaType.Trim() == "I"
                                select p);
                if (tempList.Count() == 0)
                {
                    account.I_Times = 0;
                    account.I_Amount = 0;
                }
                else
                {
                    account.I_Times = tempList.Sum((item) => item.Slices.Value);
                    account.I_Amount = tempList.Sum((item) => item.BaseFee.Value + item.ServeFee.Value + item.ExtraFee.Value); ;
                }

                tempList = (from p in phnList
                            where p.AreaType.Trim() == "C"
                            select p);
                if (tempList.Count() == 0)
                {
                    account.C_Times = 0;
                    account.C_Amount = 0;
                }
                else
                {
                    account.C_Times = tempList.Sum((item) => item.Slices.Value);
                    account.C_Amount = tempList.Sum((item) => item.BaseFee.Value + item.ServeFee.Value + item.ExtraFee.Value); ;
                }

                tempList = (from p in phnList
                            where p.AreaType.Trim() == "F"
                            select p);
                if (tempList.Count() == 0)
                {
                    account.F_Times = 0;
                    account.F_Amount = 0;
                }
                else
                {
                    account.F_Times = tempList.Sum((item) => item.Slices.Value);
                    account.F_Amount = tempList.Sum((item) => item.BaseFee.Value + item.ServeFee.Value + item.ExtraFee.Value); ;
                }

                tempList = (from p in phnList
                            where p.AreaType.Trim() == "L"
                            select p);
                if (tempList.Count() == 0)
                {
                    account.L_Times = 0;
                    account.L_Amount = 0;
                }
                else
                {
                    account.L_Times = tempList.Sum((item) => item.Slices.Value);
                    account.L_Amount = tempList.Sum((item) => item.BaseFee.Value + item.ServeFee.Value + item.ExtraFee.Value); ;
                }

                tempList = (from p in phnList
                            where p.AreaType.Trim() == "M"
                            select p);
                if (tempList.Count() == 0)
                {
                    account.M_Times = 0;
                    account.M_Amount = 0;
                }
                else
                {
                    account.M_Times = tempList.Sum((item) => item.Slices.Value);
                    account.M_Amount = tempList.Sum((item) => item.BaseFee.Value + item.ServeFee.Value + item.ExtraFee.Value); ;
                }

                tempList = (from p in phnList
                            where p.AreaType.Trim() == "O"
                            select p);
                if (tempList.Count() == 0)
                {
                    account.O_Times = 0;
                    account.O_Amount = 0;
                }
                else
                {
                    account.O_Times = tempList.Sum((item) => item.Slices.Value);
                    account.O_Amount = tempList.Sum((item) => item.BaseFee.Value + item.ServeFee.Value + item.ExtraFee.Value); ;
                }

                tempList = (from p in phnList
                            where p.AreaType.Trim() == "P"
                            select p);
                if (tempList.Count() == 0)
                {
                    account.P_Times = 0;
                    account.P_Amount = 0;
                }
                else
                {
                    account.P_Times = tempList.Sum((item) => item.Slices.Value);
                    account.P_Amount = tempList.Sum((item) => item.BaseFee.Value + item.ServeFee.Value + item.ExtraFee.Value); ;
                }

                tempList = (from p in phnList
                            where p.AreaType.Trim() == "S"
                            select p);
                if (tempList.Count() == 0)
                {
                    account.S_Times = 0;
                    account.S_Amount = 0;
                }
                else
                {
                    account.S_Times = tempList.Sum((item) => item.Slices.Value);
                    account.S_Amount = tempList.Sum((item) => item.BaseFee.Value + item.ServeFee.Value + item.ExtraFee.Value); ;
                }

                tempList = (from p in phnList
                            where p.AreaType.Trim() == "Z"
                            select p);
                if (tempList.Count() == 0)
                {
                    account.Z_Times = 0;
                    account.Z_Amount = 0;
                }
                else
                {
                    account.Z_Times = tempList.Sum((item) => item.Slices.Value);
                    account.Z_Amount = tempList.Sum((item) => item.BaseFee.Value + item.ServeFee.Value + item.ExtraFee.Value); ;
                }

                account.TotalPhn = phnList.Count();
                account.TotalFee = phnList.Sum((item) => item.BaseFee.Value + item.ServeFee.Value + item.ExtraFee.Value); ;

                account.TotalFee += account.Fee1 + account.Fee2 + account.Fee3 + account.Fee4 + account.Fee5 - account.FreeFee;

                entities.AddToNAccount(account);

                UIAccount uiAccount = new UIAccount();
                uiAccount.部门 = dept.Name.Trim();
                uiAccount.分组 = ngroup.Name.Trim();
                uiAccount.分机号码 = account.ExtensionID;
                uiAccount.月租费 = account.Fee1.ToString("0.00");
                uiAccount.功能费 = account.Fee2.ToString("0.00");
                uiAccount.维护费 = account.Fee3.ToString("0.00");
                uiAccount.其他费 = account.Fee4.ToString("0.00");
                uiAccount.月杂费 = account.Fee5.ToString("0.00");
                uiAccount.免费额 = account.FreeFee.ToString("0.00");
                uiAccount.内线计次 = account.I_Times.ToString("0.00");
                uiAccount.内线金额 = account.I_Amount.ToString("0.00");
                uiAccount.市话计次 = account.C_Times.ToString("0.00");
                uiAccount.市话金额 = account.C_Amount.ToString("0.00");
                uiAccount.国际计次 = account.F_Times.ToString("0.00");
                uiAccount.国际金额 = account.F_Amount.ToString("0.00");
                uiAccount.国内计次 = account.L_Times.ToString("0.00");
                uiAccount.国内金额 = account.L_Amount.ToString("0.00");
                uiAccount.信息计次 = account.M_Times.ToString("0.00");
                uiAccount.信息金额 = account.M_Amount.ToString("0.00");
                uiAccount.其他计次 = account.O_Times.ToString("0.00");
                uiAccount.其他金额 = account.O_Amount.ToString("0.00");
                uiAccount.IP计次 = account.P_Times.ToString("0.00");
                uiAccount.IP金额 = account.P_Amount.ToString("0.00");
                uiAccount.郊县计次 = account.S_Times.ToString("0.00");
                uiAccount.郊县金额 = account.S_Amount.ToString("0.00");
                uiAccount.专线计次 = account.Z_Times.ToString("0.00");
                uiAccount.专线金额 = account.Z_Amount.ToString("0.00");

                uiAccount.话单总次数 = account.TotalPhn;
                uiAccount.话单总金额 = account.TotalFee.ToString("0.00");
                resultList.Add(uiAccount);
            }

            var groupList = from g in entities.NGroup
                            where g.ParentType.Trim() == "Group" &&
                                  g.ParentID.Trim() == ngroup.ID.Trim()
                            select g;

            foreach (var group in groupList)
                deal(group, dept, entities, month, day, startDate, endDate, resultList);
        }

        private string findDepartmentID(Extensions extension, SanDiDbsEntities entities)
        {
            NGroup ngroup = (from g in entities.NGroup
                             where g.ID.Trim() == extension.GrpNo.Trim()
                             select g).SingleOrDefault();
            if (ngroup == null)
                return null;
            if (ngroup == null)
            {
                int i = 0;
            }
            while (ngroup.ParentType == "Group")
            {
                ngroup = (from g in entities.NGroup
                          where g.ID.Trim() == ngroup.ParentID.Trim()
                          select g).SingleOrDefault();
            }
            return ngroup.ParentID.Trim();
        }


        public ActionResult GroupPayment(string message)
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            SanDiDbsEntities entities = new SanDiDbsEntities();

            Guid userID = (Guid)Session["UserID"];
            var authroity = (from a in entities.UserAuthority
                             where a.Item == "收款" &&
                                   a.UserID == userID
                             select a).SingleOrDefault();
            if (authroity == null || !authroity.Allow)
            {
                TempData["Error"] = "你没有权限使用这个功能";
                return RedirectToAction("Error", "Shared");
            }

            MenuModel model1 = (MenuModel)Session["Menu"];
            model1.SetMenu("Billing", "Billing/Payment");

            GroupPaymentModel model = new GroupPaymentModel();
            model.Message = message;
            model.DepartmentList = (from d in entities.NDepartment
                                    orderby d.Seq
                                    select new UIDepartment()
                                    {
                                        名称 = d.Name.Trim(),
                                        ID = d.ID.Trim(),
                                    }).ToList();

            foreach (var department in model.DepartmentList)
            {
                department.分组List = new List<UIGroup>();

                var list1 = from g in entities.NGroup
                            where g.ParentType.Trim() == "Department" &&
                                  g.ParentID == department.ID
                            orderby g.Seq
                            select g;
                foreach (var group1 in list1)
                {
                    UIGroup uiGroup1 = new UIGroup();
                    uiGroup1.ID = group1.ID.Trim();
                    uiGroup1.名称 = group1.Name.Trim();
                    uiGroup1.分组List = new List<UIGroup>();

                    department.分组List.Add(uiGroup1);


                    var list2 = from g in entities.NGroup
                                where g.ParentType.Trim() == "Group" &&
                                      g.ParentID == uiGroup1.ID
                                orderby g.Seq
                                select g;
                    foreach (var group2 in list2)
                    {
                        UIGroup uiGroup2 = new UIGroup();
                        uiGroup2.ID = group2.ID.Trim();
                        uiGroup2.名称 = group2.Name.Trim();
                        uiGroup2.分组List = new List<UIGroup>();

                        uiGroup1.分组List.Add(uiGroup2);

                        var list3 = from g in entities.NGroup
                                    where g.ParentType.Trim() == "Group" &&
                                          g.ParentID == uiGroup2.ID
                                    orderby g.Seq
                                    select g;
                        foreach (var group3 in list3)
                        {
                            UIGroup uiGroup3 = new UIGroup();
                            uiGroup3.ID = group3.ID.Trim();
                            uiGroup3.名称 = group3.Name.Trim();
                            uiGroup3.分组List = new List<UIGroup>();

                            uiGroup2.分组List.Add(uiGroup3);
                        }


                    }
                }
            }

            return View(model);
        }

        //[HttpPost]
        //public ActionResult GroupPayment(PaymentModel model)
        //{
        //    try
        //    {
        //        string[] idList = model.SelectItem.Split('!');

        //        SanDiDbsEntities entities = new SanDiDbsEntities();

        //        var list = from a in entities.NAccount
        //                   where a.HasPay == false &&
        //                         idList.Contains(a.ExtensionID.Trim())
        //                   orderby a.DepartmentID, a.GroupID, a.ExtensionID, a.Month
        //                   select a;

        //        List<UIAccount> resultList = new List<UIAccount>();

        //        foreach (var item in list)
        //        {
        //            UIAccount account = new UIAccount();
        //            account.ID = item.ID;
        //            account.月 = string.Format("{0}年{1}月", item.Month.Year, item.Month.Month);
        //            var dept = (from d in entities.NDepartment
        //                        where d.ID.Trim() == item.DepartmentID.Trim()
        //                        select d).SingleOrDefault();
        //            account.部门 = (dept == null) ? "" : dept.Name.Trim();
        //            var group = (from d in entities.NGroup
        //                         where d.ID.Trim() == item.GroupID.Trim()
        //                         select d).SingleOrDefault();
        //            account.分组 = (group == null) ? "" : group.Name.Trim();
        //            account.分机号码 = item.ExtensionID.Trim();
        //            var ext = (from e in entities.Extensions
        //                       where e.ExtNo.Trim() == account.分机号码
        //                       select e).SingleOrDefault();
        //            if (ext != null && ext.UserName != null)
        //                account.用户名 = ext.UserName.Trim();

        //            account.月租费 = item.Fee1.ToString("0.00");
        //            account.功能费 = item.Fee2.ToString("0.00");
        //            account.通话费 = (item.TotalFee - item.Fee1 - item.Fee2).ToString("0.00");
        //            account.话单总次数 = item.TotalPhn;
        //            account.话单总金额 = item.TotalFee.ToString("0.00");
        //            account.IsSelected = true;

        //            resultList.Add(account);
        //        }

        //        TempData["Result"] = resultList;
        //        return RedirectToAction( "PaymentNext","Billing");
        //    }
        //    catch (Exception e)
        //    {
        //        TempData["Error"] = e.Message;
        //        return RedirectToAction("Error", "Shared");
        //    }
        //}

        public ActionResult GroupPaymentDetail(string id)
        {
            GroupPaymentDetailModel model = new GroupPaymentDetailModel();
            model.ID = id;
            SanDiDbsEntities entities = new SanDiDbsEntities();
            List<string> extList = new List<string>();
            var dept = (from d in entities.NDepartment
                        where d.ID.Trim() == id.Trim()
                        select d).SingleOrDefault();

            if (dept == null)
            {
                var ngroup = (from g in entities.NGroup
                              where g.ID.Trim() == id.Trim()
                              select g).SingleOrDefault();
                if (ngroup == null)
                {
                    TempData["Error"] = "没有找到分组";
                    return RedirectToAction("Error", "Shared");
                }
                model.分组 = ngroup.Name.Trim();
                var temp = ngroup;
                while (dept == null)
                {
                    if (temp.ParentType.Trim() == "Group")
                    {
                        temp = (from g in entities.NGroup
                                where g.ID.Trim() == temp.ParentID.Trim()
                                select g).SingleOrDefault();
                    }
                    else if (temp.ParentType.Trim() == "Department")
                    {
                        dept = (from g in entities.NDepartment
                                where g.ID.Trim() == temp.ParentID.Trim()
                                select g).SingleOrDefault();
                    }
                    else
                        return null;
                }
                
                
                getExtList(extList, id, entities);
            }
            else 
            {
                var groupList = (from g in entities.NGroup
                                 where g.ParentType.Trim() == "Department" &&
                                       g.ParentID.Trim() == id.Trim()
                                 select g);
                foreach(var group in groupList)
                    getExtList(extList, group.ID, entities);
            }
            model.部门 = dept.Name.Trim();
            var accountList = (from a in entities.NAccount
                               where !a.HasPay &&
                                     extList.Contains(a.ExtensionID.Trim())
                               select a);
            Dictionary<string, GroupPaymentItem> dicKey = new Dictionary<string, GroupPaymentItem>();
            model.AccountList = new List<GroupPaymentItem>();
            foreach (var account in accountList)
            {
                GroupPaymentItem item = null;
                string key = string.Format("{0}年{1}月", account.Month.Year, account.Month.Month);
                if (dicKey.ContainsKey(key))
                    item = dicKey[key];
                else
                {
                    item = new GroupPaymentItem();
                    item.Year = account.Month.Year;
                    item.Month = account.Month.Month;
                    model.AccountList.Add(item);
                    dicKey.Add(key, item);
                }
                item.m月租费 += account.Fee1;
                item.m功能费 += account.Fee2;
                item.m通话费 += account.TotalFee - account.Fee1 - account.Fee2;
                item.m总次数 += account.TotalPhn;
                item.m总金额 += account.TotalFee;
                model.m总金额 += account.TotalFee;
            }

            foreach (var item in model.AccountList)
            {
                item.功能费 = item.m功能费.ToString("0.00");
                item.月租费 = item.m月租费.ToString("0.00");
                item.通话费 = item.m通话费.ToString("0.00");
                item.总金额 = item.m总金额.ToString("0.00");
                item.总次数 = item.m总次数.ToString();
            }
            model.总金额 = model.m总金额.ToString("0.00");
            model.AccountList = (from i in model.AccountList
                                 orderby i.Year, i.Month
                                 select i).ToList();

            return View(model);
        }

        [HttpPost]
        public ActionResult GroupPaymentDetail(GroupPaymentDetailModel model)
        {
            SanDiDbsEntities entities = new SanDiDbsEntities();

            var ngroup = (from g in entities.NGroup
                          where g.ID.Trim() == model.ID
                          select g).SingleOrDefault();
            if (ngroup == null)
            {
                TempData["Error"] = "没有找到分组";
                return RedirectToAction("Error", "Shared");
            }
            
            List<string> extList = new List<string>();
            getExtList(extList, model.ID, entities);


            var tempList = model.MonthTxt.Split('-');
            for (int i = 0; i < tempList.Length; i = i + 2)
            {
                int year = Convert.ToInt32(tempList[i]);
                int month = Convert.ToInt32(tempList[i + 1]);

                DateTime dateTime = new DateTime(year, month, 1);

                var accountList = (from a in entities.NAccount
                               where a.Month == dateTime &&
                                     extList.Contains(a.ExtensionID.Trim())
                               select a);

                foreach(var account in accountList)
                    account.HasPay = true;
            }

            entities.SaveChanges();

            return RedirectToAction("GroupPayment", "Billing", new { message = "操作成功！" });
        }

        private void getExtList(List<string> extList, string id, SanDiDbsEntities entities)
        {
            extList.AddRange(from e in entities.Extensions
                             where e.GrpNo.Trim() == id
                             select e.ExtNo.Trim());
            var groupList = (from g in entities.NGroup
                             where g.ParentType.Trim() == "Group" &&
                                   g.ParentID.Trim() == id
                             select g);
            foreach (var ngroup in groupList)
                getExtList(extList, ngroup.ID.Trim(), entities);
        }

        //[HttpPost]
        //public ActionResult GroupPaymentNext(PaymentNextModel model)
        //{
        //    try
        //    {
        //        string[] strs = model.SelectItem.Split('!');
        //        List<Guid> idList = new List<Guid>();
        //        foreach (var str in strs)
        //            idList.Add(Guid.Parse(str));

        //        SanDiDbsEntities entities = new SanDiDbsEntities();
        //        var list = from a in entities.NAccount
        //                   where idList.Contains(a.ID)
        //                   select a;
        //        foreach (var item in list)
        //            item.HasPay = true;

        //        entities.SaveChanges();

        //        return RedirectToAction("Payment", "Billing", new { message = "操作成功！" });
        //    }
        //    catch (Exception e)
        //    {
        //        TempData["Error"] = e.Message;
        //        return RedirectToAction("Error", "Shared");
        //    }
        //}

        public ActionResult PaymentPrint(string groupID, string monthTxt)
        {
            PaymentPrintModel model = new PaymentPrintModel();
            SanDiDbsEntities entities = new SanDiDbsEntities();

            PaymentPage paymentPage = new PaymentPage();
            List<string> extList = new List<string>();
            var dept = (from d in entities.NDepartment
                        where d.ID.Trim() == groupID.Trim()
                        select d).SingleOrDefault();
            if (dept == null)
            {
                var ngroup = (from g in entities.NGroup
                              where g.ID.Trim() == groupID.Trim()
                              select g).SingleOrDefault();
                if (ngroup == null)
                {
                    TempData["Error"] = "没有找到分组";
                    return RedirectToAction("Error", "Shared");
                }
                paymentPage.分组 = ngroup.Name.Trim();
                var temp = ngroup;
                while (dept == null)
                {
                    if (temp.ParentType.Trim() == "Group")
                    {
                        temp = (from g in entities.NGroup
                                where g.ID.Trim() == temp.ParentID.Trim()
                                select g).SingleOrDefault();
                    }
                    else if (temp.ParentType.Trim() == "Department")
                    {
                        dept = (from g in entities.NDepartment
                                where g.ID.Trim() == temp.ParentID.Trim()
                                select g).SingleOrDefault();
                    }
                    else
                        return null;
                }
                getExtList(extList, groupID, entities);
            }
            else
            {
                var groupList = (from g in entities.NGroup
                                 where g.ParentType.Trim() == "Department" &&
                                       g.ParentID.Trim() == groupID.Trim()
                                 select g);
                foreach(var group in groupList)
                    getExtList(extList, group.ID.Trim(), entities);
            }
            paymentPage.部门 = dept.Name.Trim();
            
            List<NAccount> accountList = new List<NAccount>(); ;
            var tempList = monthTxt.Split('-');
            for (int i = 0; i < tempList.Length; i=i+2)
            {
                int year = Convert.ToInt32(tempList[i]);
                int month = Convert.ToInt32(tempList[i+1]);

                DateTime dateTime = new DateTime(year,month,1);

                var account = (from a in entities.NAccount
                               where a.Month == dateTime &&
                                     extList.Contains(a.ExtensionID.Trim())
                               select a);

                accountList.AddRange(account);
            }

            DateTime minDateTime = (from a in accountList
                                    orderby a.Month
                                    select a.Month).FirstOrDefault();
            DateTime maxDateTime = (from a in accountList
                                    orderby a.Month descending
                                    select a.Month).FirstOrDefault();
            paymentPage.计费周期 = string.Format("{0} ~ {1}", minDateTime.ToShortDateString(), maxDateTime.AddMonths(1).AddDays(-1).ToShortDateString());

            Dictionary<string, PaymentItem> dicKey = new Dictionary<string, PaymentItem>();
            List<PaymentItem> list = new List<PaymentItem>();
            foreach (var account in accountList)
            {
                PaymentItem item = null;
                string key = account.ExtensionID.Trim();
                if (dicKey.ContainsKey(key))
                    item = dicKey[key];
                else
                {
                    item = new PaymentItem();
                    item.电话号码 = account.ExtensionID.Trim();
                    var extension = (from e in entities.Extensions
                                     where e.ExtNo.Trim() == item.电话号码
                                     select e).SingleOrDefault();
                    item.名称 = extension.UserName == null ? string.Empty : extension.UserName.Trim();
                    list.Add(item);
                    dicKey.Add(key, item);
                }
                item.m月租费 += account.Fee1;
                item.m功能费 += account.Fee2;
                item.m通话费 += account.TotalFee - account.Fee1 - account.Fee2;
                item.m通话次数 += account.TotalPhn;
                item.m总费用 += account.TotalFee;
                paymentPage.国内次数 += account.L_Times;
                paymentPage.m国内金额 += account.L_Amount;
                paymentPage.IP次数 += account.P_Times;
                paymentPage.mIP金额 += account.P_Amount;
                paymentPage.郊县次数 += account.S_Times;
                paymentPage.m郊县金额 += account.S_Amount;
                paymentPage.内线次数 += account.I_Times;
                paymentPage.m内线金额 += account.I_Amount;
                paymentPage.市话次数 += account.C_Times;
                paymentPage.m市话金额 += account.C_Amount;
                paymentPage.信息次数 += account.M_Times;
                paymentPage.m信息金额 += account.M_Amount;
                paymentPage.专线次数 += account.Z_Times;
                paymentPage.m专线金额 += account.Z_Amount;
                paymentPage.国际次数 += account.F_Times;
                paymentPage.m国际金额 += account.F_Amount;
                paymentPage.其他次数 += account.O_Times;
                paymentPage.m其他金额 += account.O_Amount;
                paymentPage.总计通话次数 += account.TotalPhn;
                paymentPage.m总费用 += account.TotalFee;

                paymentPage.m月租费 += account.Fee1;
                paymentPage.m功能费 += account.Fee2;
                paymentPage.m收费项小计 += account.Fee1 + account.Fee2;
                paymentPage.m话类小计金额 += account.L_Amount + account.P_Amount + account.S_Amount + account.I_Amount + account.C_Amount + account.M_Amount + account.F_Amount + account.O_Amount + account.Z_Amount;
                paymentPage.话类小计次数 += account.L_Times + account.P_Times + account.S_Times + account.I_Times + account.C_Times + account.M_Times + account.F_Times + account.O_Times + account.Z_Times;

                paymentPage.m总计通话费 += account.TotalFee - account.Fee1 - account.Fee2;
            }

            foreach (var item in list)
            {
                item.功能费 = item.m功能费.ToString("0.00");
                item.月租费 = item.m月租费.ToString("0.00");
                item.通话费 = item.m通话费.ToString("0.00");
                item.总费用 = item.m总费用.ToString("0.00");
                item.通话次数 = item.m通话次数.ToString();

            }
            paymentPage.国内金额 = paymentPage.m国内金额.ToString("0.00");
            paymentPage.IP金额 = paymentPage.mIP金额.ToString("0.00");
            paymentPage.郊县金额 = paymentPage.m郊县金额.ToString("0.00");
            paymentPage.内线金额 = paymentPage.m内线金额.ToString("0.00");
            paymentPage.市话金额 = paymentPage.m市话金额.ToString("0.00");
            paymentPage.信息金额 = paymentPage.m信息金额.ToString("0.00");
            paymentPage.国际金额 = paymentPage.m国际金额.ToString("0.00");
            paymentPage.其他金额 = paymentPage.m其他金额.ToString("0.00");
            paymentPage.专线金额 = paymentPage.m专线金额.ToString("0.00");
            paymentPage.总费用 = paymentPage.m总费用.ToString("0.00");
            paymentPage.月租费 = paymentPage.m月租费.ToString("0.00");
            paymentPage.功能费 = paymentPage.m功能费.ToString("0.00");
            paymentPage.国内金额 = paymentPage.m国内金额.ToString("0.00");
            paymentPage.收费项小计 = paymentPage.m收费项小计.ToString("0.00");
            paymentPage.话类小计金额 = paymentPage.m话类小计金额.ToString("0.00");
            paymentPage.总计通话费 = paymentPage.m总计通话费.ToString("0.00");
            list = (from i in list
                    orderby i.电话号码
                    select i).ToList();


            RptPaymentReport report = new RptPaymentReport();
            report.Source.DataSource = list;
            report.TotalSource.DataSource = paymentPage;
            using (MemoryStream stream = new MemoryStream())
            {
                report.ExportToHtml(stream);
                stream.Position = 0;
                using (StreamReader sr = new StreamReader(stream))
                {
                    model.Content = sr.ReadToEnd();
                }
            }

            return View(model);
        }

        public ActionResult PhonePayment()
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            SanDiDbsEntities entities = new SanDiDbsEntities();

            Guid userID = (Guid)Session["UserID"];
            var authroity = (from a in entities.UserAuthority
                             where a.Item == "收款" &&
                                   a.UserID == userID
                             select a).SingleOrDefault();
            if (authroity == null || !authroity.Allow)
            {
                TempData["Error"] = "你没有权限使用这个功能";
                return RedirectToAction("Error", "Shared");
            }

            MenuModel model1 = (MenuModel)Session["Menu"];
            model1.SetMenu("Billing", "Billing/PhonePayment");

            PhonePaymentModel model = new PhonePaymentModel();
            return View(model);
        }

        [HttpPost]
        public ActionResult PhonePayment(PhonePaymentModel model)
        {
            if (ModelState.IsValid)
            {
                return RedirectToAction("PhonePaymentNext", new { extension = model.Phone.Trim() });
            }
            return View(model);
        }

        public ActionResult PhonePaymentNext(string extension)
        {
            if (Session["User"] == null)
            {
                return this.RedirectToAction("../Account/Login");
            }

            MenuModel model1 = (MenuModel)Session["Menu"];
            model1.SetMenu("Billing", "Billing/PhonePayment");

            PhonePaymentNextModel model = new PhonePaymentNextModel();
            model.分机 = extension;
            SanDiDbsEntities entities = new SanDiDbsEntities();

            var phone = (from e in entities.Extensions
                             where e.ExtNo.Trim() == extension
                             select e).SingleOrDefault();
            if (phone == null)
            {
                TempData["Error"] = "没有找到分机";
                return RedirectToAction("Error", "Shared");
            }

            var ngroup = (from g in entities.NGroup
                          where g.ID.Trim() == phone.GrpNo.Trim()
                          select g).SingleOrDefault();
            if (ngroup == null)
            {
                TempData["Error"] = "没有找到分组";
                return RedirectToAction("Error", "Shared");
            }
            model.分组 = ngroup.Name.Trim();
            var temp = ngroup;
            NDepartment dept = null;
            while (dept == null)
            {
                if (temp.ParentType.Trim() == "Group")
                {
                    temp = (from g in entities.NGroup
                            where g.ID.Trim() == temp.ParentID.Trim()
                            select g).SingleOrDefault();
                    if(temp == null)
                    {
                        TempData["Error"] = "没有找到部门";
                        return RedirectToAction("Error", "Shared");
                    }
                }
                else if (temp.ParentType.Trim() == "Department")
                {
                    dept = (from g in entities.NDepartment
                            where g.ID.Trim() == temp.ParentID.Trim()
                            select g).SingleOrDefault();
                    if (dept == null)
                    {
                        TempData["Error"] = "没有找到部门";
                        return RedirectToAction("Error", "Shared");
                    }
                }
                else
                {
                    TempData["Error"] = "没有找到部门";
                    return RedirectToAction("Error", "Shared");
                }
            }
            model.部门 = dept.Name.Trim();

            var accountList = (from a in entities.NAccount
                               where !a.HasPay &&
                                     a.ExtensionID.Trim() == extension
                               select a);
            Dictionary<string, GroupPaymentItem> dicKey = new Dictionary<string, GroupPaymentItem>();
            model.AccountList = new List<GroupPaymentItem>();
            foreach (var account in accountList)
            {
                GroupPaymentItem item = null;
                string key = string.Format("{0}年{1}月", account.Month.Year, account.Month.Month);
                if (dicKey.ContainsKey(key))
                    item = dicKey[key];
                else
                {
                    item = new GroupPaymentItem();
                    item.Year = account.Month.Year;
                    item.Month = account.Month.Month;
                    model.AccountList.Add(item);
                    dicKey.Add(key, item);
                }
                item.m月租费 += account.Fee1;
                item.m功能费 += account.Fee2;
                item.m通话费 += account.TotalFee - account.Fee1 - account.Fee2;
                item.m总次数 += account.TotalPhn;
                item.m总金额 += account.TotalFee;
                model.m总金额 += account.TotalFee;
            }

            foreach (var item in model.AccountList)
            {
                item.功能费 = item.m功能费.ToString("0.00");
                item.月租费 = item.m月租费.ToString("0.00");
                item.通话费 = item.m通话费.ToString("0.00");
                item.总金额 = item.m总金额.ToString("0.00");
                item.总次数 = item.m总次数.ToString();
            }
            model.总金额 = model.m总金额.ToString("0.00");
            model.AccountList = (from i in model.AccountList
                                 orderby i.Year, i.Month
                                 select i).ToList();

            return View(model);
        }

        [HttpPost]
        public ActionResult PhonePaymentNext(PhonePaymentNextModel model)
        {
            SanDiDbsEntities entities = new SanDiDbsEntities();

            var phone = (from e in entities.Extensions
                         where e.ExtNo.Trim() == model.分机
                         select e).SingleOrDefault();
            if (phone == null)
            {
                TempData["Error"] = "没有找到分机";
                return RedirectToAction("Error", "Shared");
            }

            var tempList = model.MonthTxt.Split('-');
            for (int i = 0; i < tempList.Length; i = i + 2)
            {
                int year = Convert.ToInt32(tempList[i]);
                int month = Convert.ToInt32(tempList[i + 1]);

                DateTime dateTime = new DateTime(year, month, 1);

                var account = (from a in entities.NAccount
                               where a.Month == dateTime &&
                                     a.ExtensionID.Trim() == model.分机
                               select a).SingleOrDefault();

                account.HasPay = true;
            }

            entities.SaveChanges();

            TempData["Message"] = "操作成功";
            return RedirectToAction("Message", "Shared");
        }

        public ActionResult PhonePaymentPrint(string extension, string monthTxt)
        {
            PaymentPrintModel model = new PaymentPrintModel();
            SanDiDbsEntities entities = new SanDiDbsEntities();
            
            PaymentPage paymentPage = new PaymentPage();

            var phone = (from e in entities.Extensions
                         where e.ExtNo.Trim() == extension
                         select e).SingleOrDefault();
            if (phone == null)
            {
                TempData["Error"] = "没有找到分机";
                return RedirectToAction("Error", "Shared");
            }

            var ngroup = (from g in entities.NGroup
                          where g.ID.Trim() == phone.GrpNo.Trim()
                          select g).SingleOrDefault();
            if (ngroup == null)
            {
                TempData["Error"] = "没有找到分组";
                return RedirectToAction("Error", "Shared");
            }
            paymentPage.分组 = ngroup.Name.Trim();
            var temp = ngroup;
            NDepartment dept = null;
            while (dept == null)
            {
                if (temp.ParentType.Trim() == "Group")
                {
                    temp = (from g in entities.NGroup
                            where g.ID.Trim() == temp.ParentID.Trim()
                            select g).SingleOrDefault();
                }
                else if (temp.ParentType.Trim() == "Department")
                {
                    dept = (from g in entities.NDepartment
                            where g.ID.Trim() == temp.ParentID.Trim()
                            select g).SingleOrDefault();
                }
                else
                    return null;
            }
            paymentPage.部门 = dept.Name.Trim();

            List<NAccount> accountList = new List<NAccount>(); ;
            var tempList = monthTxt.Split('-');
            for (int i = 0; i < tempList.Length; i=i+2)
            {
                int year = Convert.ToInt32(tempList[i]);
                int month = Convert.ToInt32(tempList[i+1]);

                DateTime dateTime = new DateTime(year,month,1);

                var account = (from a in entities.NAccount
                               where a.Month == dateTime &&
                                     a.ExtensionID.Trim() == extension
                               select a).SingleOrDefault();

                accountList.Add(account);
            }

            DateTime minDateTime = (from a in accountList
                                    orderby a.Month
                                    select a.Month).FirstOrDefault();
            DateTime maxDateTime = (from a in accountList
                                    orderby a.Month descending
                                    select a.Month).FirstOrDefault();
            paymentPage.计费周期 = string.Format("{0} ~ {1}", minDateTime.ToShortDateString(), maxDateTime.AddMonths(1).AddDays(-1).ToShortDateString());
            

            Dictionary<string, PaymentItem> dicKey = new Dictionary<string, PaymentItem>();
            List<PaymentItem> list = new List<PaymentItem>();
            foreach (var account in accountList)
            {
                PaymentItem item = null;
                string key = account.ExtensionID.Trim();
                if (dicKey.ContainsKey(key))
                    item = dicKey[key];
                else
                {
                    item = new PaymentItem();
                    item.电话号码 = account.ExtensionID.Trim();
                    item.名称 = phone.UserName.Trim();
                    list.Add(item);
                    dicKey.Add(key, item);
                }
                item.m月租费 += account.Fee1;
                item.m功能费 += account.Fee2;
                item.m通话费 += account.TotalFee - account.Fee1 - account.Fee2;
                item.m通话次数 += account.TotalPhn;
                item.m总费用 += account.TotalFee;
                paymentPage.国内次数 += account.L_Times;
                paymentPage.m国内金额 += account.L_Amount;
                paymentPage.IP次数 += account.P_Times;
                paymentPage.mIP金额 += account.P_Amount;
                paymentPage.郊县次数 += account.S_Times;
                paymentPage.m郊县金额 += account.S_Amount;
                paymentPage.内线次数 += account.I_Times;
                paymentPage.m内线金额 += account.I_Amount;
                paymentPage.市话次数 += account.C_Times;
                paymentPage.m市话金额 += account.C_Amount;
                paymentPage.信息次数 += account.M_Times;
                paymentPage.m信息金额 += account.M_Amount;
                paymentPage.专线次数 += account.Z_Times;
                paymentPage.m专线金额 += account.Z_Amount;
                paymentPage.国际次数 += account.F_Times;
                paymentPage.m国际金额 += account.F_Amount;
                paymentPage.其他次数 += account.O_Times;
                paymentPage.m其他金额 += account.O_Amount;
                paymentPage.总计通话次数 += account.TotalPhn;
                paymentPage.总计通话次数 += account.TotalPhn;
                paymentPage.m总费用 += account.TotalFee;

                paymentPage.m月租费 += account.Fee1;
                paymentPage.m功能费 += account.Fee2;
                paymentPage.m收费项小计 += account.Fee1 + account.Fee2;
                paymentPage.m话类小计金额 += account.L_Amount + account.P_Amount + account.S_Amount + account.I_Amount + account.C_Amount + account.M_Amount + account.F_Amount + account.O_Amount + account.Z_Amount;
                paymentPage.话类小计次数 += account.L_Times + account.P_Times + account.S_Times + account.I_Times + account.C_Times + account.M_Times + account.F_Times + account.O_Times + account.Z_Times;

                paymentPage.m总计通话费 += account.TotalFee - account.Fee1 - account.Fee2;
            }

            foreach (var item in list)
            {
                item.功能费 = item.m功能费.ToString("0.00");
                item.月租费 = item.m月租费.ToString("0.00");
                item.通话费 = item.m通话费.ToString("0.00");
                item.总费用 = item.m总费用.ToString("0.00");
                item.通话次数 = item.m通话次数.ToString();

            }
            paymentPage.国内金额 = paymentPage.m国内金额.ToString("0.00");
            paymentPage.IP金额 = paymentPage.mIP金额.ToString("0.00");
            paymentPage.郊县金额 = paymentPage.m郊县金额.ToString("0.00");
            paymentPage.内线金额 = paymentPage.m内线金额.ToString("0.00");
            paymentPage.市话金额 = paymentPage.m市话金额.ToString("0.00");
            paymentPage.信息金额 = paymentPage.m信息金额.ToString("0.00");
            paymentPage.国际金额 = paymentPage.m国际金额.ToString("0.00");
            paymentPage.其他金额 = paymentPage.m其他金额.ToString("0.00");
            paymentPage.专线金额 = paymentPage.m专线金额.ToString("0.00");
            paymentPage.总费用 = paymentPage.m总费用.ToString("0.00");
            paymentPage.月租费 = paymentPage.m月租费.ToString("0.00");
            paymentPage.功能费 = paymentPage.m功能费.ToString("0.00");
            paymentPage.国内金额 = paymentPage.m国内金额.ToString("0.00");
            paymentPage.收费项小计 = paymentPage.m收费项小计.ToString("0.00");
            paymentPage.话类小计金额 = paymentPage.m话类小计金额.ToString("0.00");
            paymentPage.总计通话费 = paymentPage.m总计通话费.ToString("0.00");
            list = (from i in list
                    orderby i.电话号码
                    select i).ToList();


            RptPaymentReport report = new RptPaymentReport();
            report.Source.DataSource = list;
            report.TotalSource.DataSource = paymentPage;
            using (MemoryStream stream = new MemoryStream())
            {
                report.ExportToHtml(stream);
                stream.Position = 0;
                using (StreamReader sr = new StreamReader(stream))
                {
                    model.Content = sr.ReadToEnd();
                }
            }

            return View(model);
        }
    }
}
